package org.demo.nio.reactor.multiplethread;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * Created by tangwy on 2017/10/31.
 */
public class MultipleThreadReactor implements Runnable{
    private Selector selector;
    private ServerSocketChannel ssc;

    public MultipleThreadReactor(int port) throws IOException {
        this(new InetSocketAddress(port));
    }

    public MultipleThreadReactor(String ip, int port) throws IOException {
        this(new InetSocketAddress(ip, port));
    }

    public MultipleThreadReactor(InetSocketAddress isa) throws IOException {
        selector = Selector.open();
        ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        ssc.socket().bind(isa);
        ssc.register(selector, SelectionKey.OP_ACCEPT,new org.demo.nio.reactor.multiplethread.Acceptor(selector,ssc));
    }

    @Override
    public void run() {
        while (!Thread.interrupted()){
            try {
                selector.select();
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()){
                    SelectionKey key = iterator.next();
                    iterator.remove();
                    process(key);
                }
            } catch (IOException e) {
                //异常处理
                e.printStackTrace();
            }

        }
    }

    private void process(SelectionKey key) {
        System.out.println("process");
        //判断key是否为null
        Runnable r = (Runnable) key.attachment();
        if(r!=null){
            r.run();
        }
    }
}
